package com.zjweu.hkg.Servies.impl;

import com.mysql.cj.Session;
import com.zjweu.hkg.DAO.MessageDAO;
import com.zjweu.hkg.POJO.Message;
import com.zjweu.hkg.POJO.User;
import com.zjweu.hkg.Servies.MessageService;
import com.zjweu.hkg.Servies.UserServices;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class MessageServiceImpl implements MessageService {
    @Autowired
     MessageDAO messageDAO;

    @Autowired
    private UserServices userServices;
    @Override
    public List<Message> getHistoryMessageByFromIdAndToId(int fromId, int toId) {
        List<Message> messages=messageDAO.getHistoryMessageByFromIdAndToId(fromId,toId);
        //将对方的消息设置为已读
        for (Message message : messages) {
            if (message.getFromId() == toId& message.getIsRead() == 0) {
                message.setIsRead(1);
                messageDAO.updateMessageIsReadByMsgId(message.getMsgId());
            }
        }
        return messages;
    }

    @Override
    public List<User> getChatUsersByUserId(int userId) {
        // 获取聊天过的人的 ID 列表
        List<Integer> chatUserIds = messageDAO.getChatUserIdsByUserId(userId);
        List<User> chatUsers = new ArrayList<>();
        for (Integer chatUserId : chatUserIds) {
            // 根据 ID 获取用户信息
            User user = userServices.getUserById(chatUserId);
            if (user != null) {
                chatUsers.add(user);
            }
        }
        return chatUsers;
    }

    @Override
    public List<Message> getUnreadMsgByUserId(int userId) {
        return messageDAO.getUnreadMsgByUserId(userId);

    }
}
